<?php

namespace App\Http\Controllers\Api;

use App\Libs\Util;
use App\Models\address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AddressController extends Controller
{
    /**
     * 收货地址列表
     * @param Request $request
     */
    public function address(Request $request)
    {
        $openid = $request->openid;
        $page = $request->json('page',1);
        $list = address::lists($openid, $page);
        fun_respon(1, $list);
    }

    /**
     * 添加收货地址
     */
    public function addaddress(Request $request)
    {
        $openid = $request->openid;
        $params = $request->only(['username','phone','address']);
        if (empty($params['username']) || empty($params['phone']) || empty($params['address'])) {
            fun_respon(0, '缺少参数');
        }
        $params['openid'] = $openid;
        $res = Util::isValidMobile($params['phone']);
        if(!$res) fun_respon(0, '手机号格式不正确');
        $res = address::insert($params);
        if ($res) fun_respon(1, '添加成功');
        fun_respon(0, '添加失败');
    }

    /**
     * 修改地址
     */
    public function editaddress(Request $request)
    {
        $openid = $request->openid;
        $id = $request->json('id');
        $params = $request->only(['username','phone','address']);
        if (empty($params['username']) || empty($params['phone']) || empty($params['address'])) {
            fun_respon(0, '缺少参数');
        }
        $res = Util::isValidMobile($params['phone']);
        if(!$res) fun_respon(0, '手机号格式不正确');
        $param['ut'] = date('Y-m-d H:i:s',time());
        $res = address::where(['id'=>$id, 'openid'=>$openid])->update($params);
        if ($res) fun_respon(1, '修改成功');
        fun_respon(0, '未进行任何修改，请重试！');
    }

    /**
     * 删除地址
     */
    public function deladdress(Request $request)
    {
        $openid = $request->openid;
        $id = $request->json('id');
        $params['is_del'] = 1;
        $res = address::where(['id'=>$id, 'openid'=>$openid])->update($params);
        if ($res) fun_respon(1, '删除成功');
        fun_respon(0, '删除失败');
    }


}
